package com.ahui.ydd.controller;

import com.ahui.ydd.common.CustomException;
import com.ahui.ydd.common.R;
import com.ahui.ydd.entity.SysUser;
import com.ahui.ydd.entity.YddUser;
import com.ahui.ydd.service.YddUserService;
import com.ahui.ydd.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/home/index")
public class FrontDeskLoginController {

    @Autowired
    private YddUserService yddUserService;

    /**
     * 登录
     *
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R<Map> login(@RequestBody Map map) {
        log.info("获取用户输入数据" + map.get("mobile") + map.get("password"));

        String mobile = String.valueOf(map.get("mobile"));
        //接收前端发来的密码  将密码经md5处理
        String password = (String) map.get("password");
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //select * from sys_user where phone = ? and password = ? ;
        LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(mobile != null, YddUser::getMobile, mobile)
                .eq(password != null, YddUser::getPassword, password);

        //执行方法查询
        YddUser user = yddUserService.getOne(queryWrapper);

        //判断数据是否存在
        if (user == null) {
            throw new CustomException("账号或密码错误!");
        }

        //将结果返还给前端 将用户id和用户名存入 token
        Map tokenMap = new HashMap();
        tokenMap.put("Userid", user.getId());
        String token = JwtUtils.getToken(tokenMap);

        Map resToken = new HashMap();
        resToken.put("token", token);
        return R.success(resToken);
    }
}
